package model

import (
	"errors"
	"ginblog/utils/errmsg"
	"gorm.io/gorm"
)

type Article struct {
	Category Category `gorm:"foreignkey:Cid"`
	gorm.Model
	Title   string `gorm:"type:varchar(255);not null" json:"title"`
	Cid     int    `gorm:"type:int;not null" json:"cid"`
	Desc    string `gorm:"type:varchar(255);" json:"desc"`
	Content string `gorm:"type:longtext;" json:"content"`
	Img     string `gorm:"type:varchar(255);not null" json:"Img"`
}

// todo 新增文章
func CreateArticle(data *Article) int {

	err := db.Create(&data).Error
	if err != nil {
		return errmsg.ERROR //500
	}
	return errmsg.SUCCESS //200
}

// todo 查询分类下所有文章
func GetArticleInfoByCategory(cid int, pageSize int, pageNum int) ([]Article, int) {
	var articlelistbycategory []Article
	err := db.Preload("Category").Limit(pageSize).Offset((pageNum-1)*pageSize).Where("cid = ?", cid).Find(&articlelistbycategory).Error
	if err != nil {
		return articlelistbycategory, errmsg.ERROR
	}
	return articlelistbycategory, errmsg.SUCCESS
}

// todo 查询单个文章
func GetArticleInfo(id int) (Article, int) {
	var data Article
	err := db.Preload("Category").Where("id = ?", id).First(&data).Error
	if err != nil {
		return data, errmsg.ERROR_ARTICLE_NOT_EXIST
	}
	return data, errmsg.SUCCESS
}

// todo 查询文章列表
func GetArticleList(pageSize int, pageNum int) ([]Article, int) {

	var ArticleList []Article
	err := db.Preload("Category").Limit(pageSize).Offset((pageNum - 1) * pageSize).Find(&ArticleList).Error
	if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		return nil, errmsg.ERROR
	}
	return ArticleList, errmsg.SUCCESS
}

// todo 编辑文章
func EditArticle(id int, data *Article) int {
	var article Article
	var maps = make(map[string]interface{})
	maps["Title"] = data.Title
	maps["Cid"] = data.Cid
	maps["Desc"] = data.Desc
	maps["Content"] = data.Content
	err = db.Model(&article).Where("id = ?", id).Updates(maps).Error
	if err != nil {
		return errmsg.ERROR
	}
	return errmsg.SUCCESS
}

// todo 删除文章
func DeleteArticle(id int) int {
	var article Article
	err = db.Where("id = ?", id).Delete(&article).Error
	if err != nil {
		return errmsg.ERROR
	}
	return errmsg.SUCCESS
}
